package com.sptpc.demo1.service.impl;

import com.sptpc.demo1.model.Category;
import com.sptpc.demo1.model.Drink;
import com.sptpc.demo1.repository.CategoryRepository;
import com.sptpc.demo1.repository.DrinkRepository;
import com.sptpc.demo1.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class CategoryJpaService implements ICategoryService {
    @Autowired
    public CategoryRepository categoryRepository;
    @Autowired
    public DrinkRepository drinkRepository;
    @Override
    public List<Category> getAllCategories() {
        return categoryRepository.findAll();
    }
    @Override
    public Category getCategoryById(Integer id) {
        return categoryRepository.findById(id).orElse(null);
    }
    @Override
    public void updateCategory(Category category){
        categoryRepository.save(category);
    }
    @Override
    public void deleteCategoryId(Integer id) {

        //2.更新所有和category关联的drink
        //2.1通过category_id把关联的drink查询出来
        List<Drink> drinks=drinkRepository.findDrinksByCategory_Id(id);
        for (Drink drink : drinks) {
            //2.2把这里drink的category设置为空
            drink.setCategory(null);
            //2.3保存
            drinkRepository.save(drink);

        }
        //1.删除指定id的category
        categoryRepository.deleteById(id);
    }
}
